package com.niiwoo.civet.mobile.lanmao.handler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.account.service.AccountInvestDubboService;
import com.niiwoo.tripod.lanmao.enums.BusinessTypeEnum;
import com.niiwoo.tripod.lanmao.enums.ResponseCodeEnum;
import com.niiwoo.tripod.lanmao.enums.ResponseStatusEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by dell on 2017/11/20.
 */
@Component
@Slf4j
public class TenderNotifyHandler implements LanMaoBizNotifyHandler {

	@Reference(version = "1.0.0")
	private AccountInvestDubboService accountInvestDubboService;

	@Override
	public boolean supports(String bizType) {
		return BusinessTypeEnum.TENDER.name().equals(bizType)||BusinessTypeEnum.CREDIT_ASSIGNMENT.name().equals(bizType);
	}

	@Override
	public HandleResult handle(JSONObject json) {
		log.info("网关投资回调参数：" + JSON.toJSONString(json));
		String requestNo = json.getString("requestNo");
		Byte code = json.getByte("code");
		String status = json.getString("status");
		String errorCode = json.getString("errorCode");
		String errorMessage = json.getString("errorMessage");
		HandleResult handleResult = new HandleResult();
		try {
			Long investOrderId = accountInvestDubboService.accountInvestExternalHandle(requestNo, code, status, errorCode, errorMessage);
			handleResult.setRequestNo(requestNo);
			handleResult.setOrderId(investOrderId);
			if (ResponseCodeEnum.SUCCESS.getValue().equals(code) && ResponseStatusEnum.SUCCESS.getValue().equals(status)) {
				handleResult.setNeedAck(true);
				handleResult.setMessage("处理成功");
				Map<String, String> data = new HashMap<>();
				data.put("investOrderId", String.valueOf(investOrderId));
				handleResult.setData(data);
			} else {
				handleResult.setNeedAck(false);
				handleResult.setMessage(json.getString("errorMessage"));
			}
		} catch (Exception e) {
			log.error("网关投资回调处理异常" + JSON.toJSONString("json"), e);
			if (e instanceof BizException) {
				throw (BizException) e;
			}
			throw new BizException("SYS9999");
		}
		return handleResult;
	}
}
